package com.ywwxhz.app;

import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.ActionBar.LayoutParams;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;

import com.readystatesoftware.systembartint.SystemBarTintManager;
import com.ywwxhz.PkgMgr.R;
import com.ywwxhz.model.AppInfo;
import com.ywwxhz.model.Category;
import com.ywwxhz.util.FileUtil;
import com.ywwxhz.util.Util;
import com.ywwxhz.view.tabbar.TabBarView;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class MainActivity extends FragmentActivity {
    private TabBarView tabBarView;
    private List<ApplicationFragment> fragments;
    private Category systemApps;
    private Category userApps;
    private PackageManager pm;
    private ViewPager mPager;
    private SystemBarTintManager tintManager;

    @SuppressLint("InflateParams")
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.package_layout);
        pm = this.getPackageManager(); // 获得PackageManager对象
        systemApps = new Category(getString(R.string.package_system_application));
        userApps = new Category(getString(R.string.package_user_application));
        fragments = new ArrayList<ApplicationFragment>();
        fragments.add(new ApplicationFragment().setCategory(userApps));
        fragments.add(new ApplicationFragment().setCategory(systemApps));
        initActionBar();

        mPager = (ViewPager) findViewById(R.id.pagerContent);

        mPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset,
                                       int positionOffsetPixels) {
                tabBarView.setSelectedTab(position);
                tabBarView.setOffset(positionOffset);
            }

            @Override
            public void onPageSelected(int position) {
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });


        mPager.setAdapter(new MainPageAdapter(getSupportFragmentManager()));
        new GetList().execute();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            Util.setTranslucentStatus(this);
            tintManager = new SystemBarTintManager(this);
            tintManager.setStatusBarTintEnabled(true);
            tintManager.setNavigationBarTintEnabled(true);
            tintManager.setStatusBarTintResource(R.color.package_statusbar_bg);
            tintManager.setNavigationBarTintColor(Color.TRANSPARENT);
        }
    }

    private void initActionBar() {
        LayoutInflater inflator = (LayoutInflater) this
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        tabBarView = (TabBarView) inflator.inflate(R.layout.package_tabbars, null);
        tabBarView.setStripColor(getResources().getColor(
                android.R.color.holo_orange_light));

        getActionBar().setDisplayShowCustomEnabled(true);
        ActionBar.LayoutParams lp = new ActionBar.LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
        lp.gravity = Gravity.END;
        getActionBar().setCustomView(tabBarView, lp);
    }

    public void queryAppInfo() {
        List<PackageInfo> appInfos = pm
                .getInstalledPackages(PackageManager.GET_UNINSTALLED_PACKAGES);
        Collections.sort(appInfos, new Comparator<PackageInfo>() {

            @Override
            public int compare(PackageInfo lhs, PackageInfo rhs) {
                return lhs.applicationInfo
                        .loadLabel(pm)
                        .toString()
                        .compareTo(rhs.applicationInfo.loadLabel(pm).toString());
            }
        });
        systemApps.clear();
        userApps.clear();
        for (PackageInfo app : appInfos) {
            String pkgName = app.packageName; // 获得应用程序的包名
            String appLabel = (String) app.applicationInfo.loadLabel(pm); // 获得应用程序的Label
            Drawable icon = app.applicationInfo.loadIcon(pm); // 获得应用程序图标
            // 创建一个AppInfo对象，并赋值
            AppInfo appInfo = new AppInfo();
            appInfo.setLabel(appLabel);
            appInfo.setPkgName(pkgName);
            appInfo.setAppIcon(icon);
            appInfo.setSourceDir(app.applicationInfo.sourceDir);
            appInfo.setVersionCode(app.versionCode);
            appInfo.setVersion(app.versionName);
            if (FileUtil.isExist(this, pkgName, app.versionCode)) {
                appInfo.setBackup(true);
            } else {
                appInfo.setBackup(false);
            }

            // 非系统程序
            if ((app.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) <= 0) {
                appInfo.setType(0);// user
                userApps.add(appInfo);
            }
            // 本来是系统程序，被用户手动更新后，该系统程序也成为第三方应用程序了
            else if ((app.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0) {
                appInfo.setType(0);// user
                userApps.add(appInfo);
            } else {
                appInfo.setType(1);// system
                systemApps.add(appInfo);
            }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.package_menu, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_flush:
                new GetList().execute();
                break;
            case R.id.menu_setting:
                startActivity(new Intent(this, SettingsActivity.class));
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    public SystemBarTintManager getSystemBarTintManager() {
        return tintManager;
    }

    private class GetList extends AsyncTask<Void, Void, Void> {

        @Override
        protected Void doInBackground(Void... params) {
            queryAppInfo(); // 查询所有应用程序信息
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            fragments.get(0).notifyDataSetChange();
            fragments.get(1).notifyDataSetChange();
        }

    }

    public class MainPageAdapter extends FragmentPagerAdapter {

        public MainPageAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public int getCount() {
            return fragments.size();
        }

        @Override
        public Fragment getItem(int position) {
            return fragments.get(position);
        }
    }
}
